<template>
    <!-- 添加或修改菜单分组资料 -->
    <el-dialog :title="title" :visible.sync="visible" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div style="margin-bottom: 15px;font-size: 20px;">
          <b>菜单分组：{{ infoData.groupName }}</b>
        </div>
        <el-form-item label="图标" prop="icon" :class="{'hiddenupload':iconShowList.length}">
          <el-upload accept=".jpg,.png" :action="uploadImgUrl" :file-list="iconShowList" :show-file-list="true" list-type="picture-card" :limit="1" :on-success="handleUploadSuccess2" :on-remove="handleRemove2" :on-preview="handlePictureCardPreview" :headers="headers">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item><br />
        <el-form-item label="简介" prop="jianjie">
          <el-input maxlength="50" v-model="form.jianjie" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="说明" prop="shuoming">
          <el-input type="textarea" :rows="4" maxlength="200" v-model="form.shuoming" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="封面图" prop="titleImg" :class="{'hiddenupload':imgShowList.length}">
          <el-upload accept=".jpg,.png" :action="uploadImgUrl" :file-list="imgShowList" :show-file-list="true" list-type="picture-card" :limit="1" :on-success="handleUploadSuccess" :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :headers="headers">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item><br />
        <el-form-item label="详情图片" class="uploader">
          <div class="">
            <!-- 自定义拖拽排序 -->
            <draggable v-model="imgFileList">
              <transition-group class="uploader_group">
                <div v-for="(item, index) in imgFileList" :key="item.url" class="upload-list">
                  <img v-if="item.url" style="width: 100%; height: 100%" :src="
                                item.url.indexOf('blob:') > -1
                                  ? item.response && item.response.data
                                    ? item.response.data.filePath
                                    : item.url
                                  : item.url
                              " />
                  <img class="imgs" v-if="item.url" style="width: 30px" src="../../../assets/img/shangchuan.png" alt="" />
                  <div class="icon-container">
                    <span v-if="item.url" @click="handlePreviewNew(index)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span @click="handleRemove3(item.url)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </div>
                </div>
              </transition-group>
            </draggable>
            <el-upload :action="uploadImgUrl" :file-list="imgFileList" list-type="picture-card" :show-file-list="false" :on-preview="handlePictureCardPreview" :on-exceed="uploadNumber" :multiple="true" :drag="true" :on-success="handleUploadSuccess3" :limit="20" accept="image/png, image/jpeg"
                       :on-remove="handleRemove3" :http-request="uploadImgs">
              <img class="uploadbg" src="https://imgage.maimaihao.com/yuduhulian/erp/static/img/uploadBg/infoImgBg.png" alt="" />
            </el-upload>

          </div>

        </el-form-item><br />

        <el-form-item label="上传视频" class="uploader">
          <el-upload v-loading="videoLoading" class="upload-demo" :headers="headers" action="#" :before-upload="beforeUploadVideo" :http-request="uploadVideoFn" :on-success="handleVideoSuccess" :limit="1" accept="video/mp4, video/mpeg4" v-if="!form.video">
            <img class="uploadbg" src="https://imgage.maimaihao.com/yuduhulian/erp/static/img/uploadBg/videoBg.png" alt="" />
          </el-upload>
          <div class="video-view radius flex" v-if="form.video">
            <video controls :src="form.video"></video>
            <span class="el-icon-delete" @click="handleVideoRemove"></span>
          </div>
          <div class="colorred font12">视频格式:MP4格式 尺寸比例:16:9;请上传100MB以内的视频</div>
        </el-form-item><br />

        <el-form-item label="详细介绍">
          <div v-if="showEditor" style="border: 1px solid #ccc; margin-top:10px">
            <myEditor v-model="form.xiangqing"></myEditor>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
</template>

<script>
import { getNotice, addNotice, updateNotice } from "@/api/system/notice";
import myEditor from "@/components/WangEditor/index.vue";
import { uploadFileFn } from "@/api/upload";
import { getToken } from "@/utils/auth";
import draggable from "vuedraggable";
import { getMenuGroupDetail, updateJieShao } from "@/api/system/menuGroup.js";
export default {
  name: "Notice",
  dicts: ["sys_notice_status", "sys_notice_type"],
  components: { myEditor, draggable },
  data() {
    return {
      title: "",
      // 遮罩层
      loading: true,
      // 是否显示弹出层
      visible: false,
      showEditor:false,
      // 表单参数
      form: {
        jianjie: "",
        shuoming: "",
        icon: "",
        titleImg: "",
        xqImg: "",
        video: "",
        xiangqing: "",
      },
      // 表单校验
      rules: {
        noticeTitle: [
          { required: true, message: "公告标题不能为空", trigger: "blur" },
        ],
        noticeType: [
          { required: true, message: "公告类型不能为空", trigger: "change" },
        ],
      },
      infoData: "",
      isEdit: false,
      // 封面图
      imgShowList: [],
      uploadImgUrl: "",
      headers: {},
      // 图标
      iconShowList: [],
      // 视频
      videoLoading: false,
      // 详情图
      imgFileList: [],
      newImages: [],
    };
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
  },

  methods: {
    open(groupId) {
      this.reset();
      this.form.groupId = groupId;
      this.visible = true;
      this.title = "分组详情";
      this.iconShowList = []
      this.imgShowList = []
      this.imgFileList = []
      this.newImages = []
      // 回显
      this.getGroupDetail(groupId);
    },
    getGroupDetail(groupId) {
      getMenuGroupDetail(groupId).then((res) => {
        this.infoData = { ...res.data };
        this.form = {
          groupId: this.infoData.groupId,
          jianjie: this.infoData.jianjie,
          shuoming: this.infoData.shuoming,
          icon: this.infoData.icon,
          titleImg: this.infoData.titleImg,
          xqImg: this.infoData.xqImg,
          video: this.infoData.video,
          xiangqing: this.infoData.xiangqing,
        };
        this.$nextTick(()=>{
          this.showEditor = true
        })
        if (this.infoData.icon) {
          this.iconShowList = [
            {
              url: this.infoData.icon,
              name: "",
            },
          ];
        }
        if (this.infoData.titleImg) {
          this.imgShowList = [
            {
              url: this.infoData.titleImg,
              name: "",
            },
          ];
        }
        if (this.infoData.xqImg) {
          const arr = JSON.parse(this.infoData.xqImg);
          this.imgFileList = [...arr];
        }
      });
    },

    // 取消按钮
    cancel() {
      this.visible = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 处理详情图片
          if (this.newImages && this.newImages.length) {
            let newArr = [];
            this.newImages.forEach((img) => {
              newArr.push({
                name: img.name,
                url: img.response.data.filePath,
              });
            });
            this.form.xqImg = JSON.stringify(this.imgFileList.concat(newArr));
          } else {
            this.form.xqImg = JSON.stringify(this.imgFileList);
          }
          updateJieShao(this.form).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.msg);
              this.visible = false
              this.$parent.getList()
            }
          });
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        jianjie: "",
        shuoming: "",
        icon: "",
        titleImg: "",
        xqImg: "",
        video: "",
        xiangqing: "",
      };
      this.resetForm("form");
    },

    handleUpdate(row) {
      this.reset();
      const noticeId = row.noticeId;
      getNotice(noticeId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改公告";
      });
    },

    // 图标 上传成功
    handleUploadSuccess2(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.iconShowList = [{ url: res.data.filePath, name: "" }];
        this.form.icon = res.data.filePath;
      }
    },
    // 图标 删除
    handleRemove2(response, fileList, file) {
      this.iconShowList = [];
      this.form.icon = "";
    },

    // 封面图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.imgShowList = [{ url: res.data.filePath, name: "" }];
        this.form.titleImg = res.data.filePath;
      }
    },
    // 封面图片删除
    handleRemove(response, fileList, file) {
      this.imgShowList = [];
      this.form.titleImg = "";
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },

    //详情图 处理图片预览效果
    handlePreviewNew(index) {
      let arr = [];
      this.imgFileList.map((item) => {
        arr.push(item.url);
      });
      this.$viewerApi({
        images: arr,
        options: {
          initialViewIndex: index,
        },
      });
    },
    // 详情图片上传成功
    handleUploadSuccess3(res, file, fileList) {
      if (fileList.every((item) => item.status == "success")) {
        let tempArr = this.imgFileList.map((m) => {
          return m.url;
        });
        fileList.forEach((t) => {
          if (
            t.url.indexOf("blob:") > -1 &&
            t.response &&
            t.response.data &&
            t.response.data.filePath
          ) {
            if (!tempArr.includes(t.response.data.filePath)) {
              this.imgFileList.push({
                url: t.response.data.filePath,
                name: "",
              });
            }
            return true;
          }
        });
      }
    },
    // 详情图片删除
    handleRemove3(url) {
      const that = this;
      this.imgFileList.forEach(function (element, key) {
        if (element.url === url) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });

      this.newImages.forEach(function (element, key) {
        if (element.url === url) {
          that.newImages.splice(key, 1); //新上传的图片
        }
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传20张图片");
    },
    // 上传图片
    async uploadImgs(file) {
      // console.log("%c Line:466 🍆 压缩前file", "color:#2eafb0", file);
      // 获取压缩后的文件流
      // let compreeBolb = await this.compressImage(file);
      // ////console.log("%c Line:468 🎂 压缩后compreeBolb", "color:#33a5ff", compreeBolb);
      // const formData = new FormData();
      // formData.append("file", compreeBolb); //压缩后的文件会自动转换成二进制文件流类型
      //上传图片到后台
      try {
        // let uploadImg = await postUpload(formData);
        const resFile = await uploadFileFn(file.file, 1);
        const imgUrl = qiniu.imageMogr2(
          {
            strip: true, // 布尔值，是否去除图片中的元信息
            quality: 90, // 图片质量，取值范围1-100
            format: "jpg", // 新图的输出格式，取值范围：jpg，gif，png，webp等
          },
          resFile.key,
          resFile.domain
        );
        file.data = {
          filePath: decodeURIComponent(imgUrl),
        };
        file.code = 200;
        return file;
      } catch {
        file.code = 500;
        return file;
      }
    },

    // 上传视频前
    beforeUploadVideo(file) {
      if (file.size / 1024 / 1024 > 100) {
        this.$message.error("上传的视频不能超过100MB！请处理后再传！");
        return false;
      } else {
        return true;
      }
    },
    // 上传视频
    async uploadVideoFn(file) {
      //上传到后台
      this.videoLoading = true;
      try {
        const resFile = await uploadFileFn(file.file, 1);
        file.data = {
          filePath: resFile.domain + resFile.key,
          fileName: resFile.key,
        };
        // file.data = {
        //   filePath: uploadImg.filePath,
        //   fileName: uploadImg.fileName,
        // };
        file.code = 200;
        this.videoLoading = false;
        return file;
      } catch {
        file.code = 500;
        this.videoLoading = false;
        return file;
      }
    },
    // 上传视频成功
    handleVideoSuccess(res, file) {
      // console.log("%c Line:857 🍤 res", "color:#ed9ec7", res);
      if (res.code == 200) {
        this.$set(this.form, "video", res.data.filePath);
      }
    },
    // 删除视频
    handleVideoRemove() {
      this.$set(this.form, "video", null);
    },
  },
};
</script>
<style lang="scss" scoped>
.uploader {
  // display: flex;
  // align-items: center;
  // flex-wrap: wrap;
  .uploader_group {
    display: flex;
    flex-wrap: wrap;
  }
  .uploadbg {
    width: $uploadWidth;
    height: $uploadHeight;
  }
  .video-view {
    width: 324px;
    height: $uploadHeight;
    // position: relative;
    // background: #409eff;
    align-items: flex-start;
    .el-icon-delete {
      width: 30px;
      height: 30px;
      flex-shrink: 0;
      font-size: 20px;
      margin-left: 10px;
      color: #333;
      cursor: pointer;
      // &:hover {
      //   color: $primary;
      // }
      // color: $fff;
    }
    video {
      width: 294px;
      height: 165px;
      border-radius: 10px;
    }
  }
  ::v-deep .el-upload-dragger {
    width: $uploadWidth;
    height: $uploadHeight;
    border: none;
  }
  ::v-deep .el-upload--picture-card {
    width: $uploadWidth;
    height: $uploadHeight;
    border: none;
  }
  ::v-deep .el-upload-list--picture-card .el-upload-list__item {
    width: $uploadWidth;
    height: $uploadHeight;
  }

  .upload-list {
    margin-right: 10px;
    margin-bottom: 10px;
    width: 294px;
    height: 165px;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #eee;
    position: relative;

    &:hover {
      .icon-container {
        display: block;
        transition: all 0.5s;
      }
    }

    .icon-container {
      position: absolute;
      display: none;
      transition: all 0.5s;
      width: 100%;
      height: 100%;
      line-height: 150px;
      color: #fff;
      font-size: 20px;
      text-align: center;
      border-radius: 8px;
      top: 0;
      left: 0;
      background-color: rgba(0, 0, 0, 0.5);
      cursor: pointer;

      span {
        margin: 0 10px;
        cursor: pointer;
      }
    }
  }

  .imgs {
    position: absolute;
    top: 0;
    right: 0;
  }
}
</style>